package cn.lk1234.imt.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.lk1234.imt.bean.UserInfo;
import cn.lk1234.imt.dao.dbtool.BaseDAO;
import cn.lk1234.imt.dao.dbtool.Column;
import cn.lk1234.imt.dao.dbtool.ColumnType;
import cn.lk1234.imt.dao.dbtool.DBTools;
import cn.lk1234.imt.dao.dbtool.DBTools.DBQuery;
import cn.lk1234.imt.dao.dbtool.MapBean;
import cn.lk1234.imt.dao.dbtool.Param;
import cn.lk1234.imt.utils.CommonUtils;

@Transactional
@Repository("userDao")
public class UserDao extends BaseDAO {

	@Autowired
	public DBTools DBTools;

	/**
	 * 根据用户名和密码去查找用户
	 * （登录用）
	 * @param user 用户提交的用户名密码
	 * @return 返回查询到的结果列表（最多1个）
	 */
	public List<MapBean> getUserByUsernameAndPassword(UserInfo user) throws SQLException {
		//新建一个参数列表
		List<Param> pList = new ArrayList<Param>();
		//向列表中加入参数
		pList.add(new Param(user.getUserName(), ColumnType.VARCHAR));
		pList.add(new Param(user.getUserPwd(), ColumnType.VARCHAR));
		//拼接Sql并执行，将执行的结果，用工具类DBTools保存到MapBean列表中 (USER_TYPE是用户类型)
		List<MapBean> dataList = DBTools.table("tb_userinfo")
				.column("USER_NAME,USER_NICK,IS_FORBID,USER_PIC_URL")
				.where(" USER_NAME = ? AND USER_PWD = ? ", pList)
				.select();
		return dataList;
	}
	
	/**
	 * 添加用户
	 * @param user
	 * @return 成功1，不成功0
	 */
	public int addUser(UserInfo user) throws SQLException {
		
		int r = 0;
		List<Column> cList = new ArrayList<Column>();
		// 一定不为空的字段
		// 用户登录名
		cList.add(new Column("USER_NAME", user.getUserName(), ColumnType.VARCHAR));
		// TODO 此处应加密处理
		// 用户登录密码
		cList.add(new Column("USER_PWD", user.getUserPwd(), ColumnType.VARCHAR));
		// 用户昵称
		cList.add(new Column("USER_NICK", user.getUserNick(), ColumnType.VARCHAR));
		// 用户类型
		cList.add(new Column("USER_TYPE", user.getUserType(), ColumnType.VARCHAR));
		// 是否禁用
		cList.add(new Column("IS_FORBID", user.getIsForbid(), ColumnType.VARCHAR));
		// 创建时间
		cList.add(new Column("CREAT_TIME", user.getCreatTime(), ColumnType.TIMESTAMP));
		
		// 不确定是否为空的字段
		// 用户邮箱
		if (StringUtils.isNotEmpty(user.getUserEmail())) {
			cList.add(new Column("USER_EMAIL", user.getUserEmail(), ColumnType.VARCHAR)); //
		}
		// 用户电话
		if (StringUtils.isNotEmpty(user.getUserPhone())) {
			cList.add(new Column("USER_PHONE", user.getUserPhone(), ColumnType.VARCHAR));
		}
		// 用户头像图片路径
		if (StringUtils.isNotEmpty(user.getUserPicUrl())) {
			cList.add(new Column("USER_PIC_URL", user.getUserPicUrl(), ColumnType.VARCHAR)); //
		}
		// 用户描述
		if (StringUtils.isNotEmpty(user.getUserDescription())) {
			cList.add(new Column("USER_DESCRIPTION", user.getUserDescription(), ColumnType.VARCHAR)); //
		}
		
		//执行SQL语句
		r = DBTools.table("tb_userinfo").add(cList);

		return r;
	}
	
	/**
	 * 
	 * 根据条件查询用户部分信息
	 * 查询结果包括【编号】【登录名】【昵称】【类型】【是否禁用】【创建时间】【最后登录时间】
	 * 
	 */
	public List<MapBean> getUserList(UserInfo user) throws SQLException {
		
		//准备好要查询的表和字段
		DBQuery dbq = DBTools.table("tb_userinfo")
				.column("USER_NO,USER_NAME,USER_NICK,USER_TYPE,IS_FORBID,CREAT_TIME,LAST_LOGIN_TIME");
		
		//新建一个参数列表
		List<Param> pList = new ArrayList<Param>();
		//新建一个SQL语句的WHERE部分
		String whereStr = " 1 = 1 ";
		//向列表中加入参数
		//用户名模糊查询
		if(StringUtils.isNotBlank(user.getUserName())){
			whereStr += "AND USER_NAME LIKE ? ";
			pList.add(new Param("%" + user.getUserName()+ "%", ColumnType.VARCHAR));
		}
		
		//如果有查询条件，就拼接SQL
		if(StringUtils.isNotBlank(whereStr) && pList.size() > 0){
			dbq.where(whereStr, pList);
		}
		
		dbq.order("USER_NO DESC");
		
		List<MapBean> dataList = dbq.select();
		return dataList;
	}
	
	/**
	 * 根据用户编号，获取用户详细信息
	 * @param user
	 * @return
	 */
	public List<UserInfo> getUserById(UserInfo user) throws SQLException {
		
		String sqlBase = "SELECT USER_NO,USER_NAME,USER_PWD,USER_NICK,USER_TYPE,IS_FORBID,CREAT_TIME,LAST_LOGIN_TIME"
				+ " FROM tb_userinfo "
				+ " WHERE USER_NO = ? ";
		Integer userNo = user.getUserNo();
		Object paramsBase[] = new Object[] { userNo };
		List<UserInfo> userList = new ArrayList<UserInfo>();
		try {
			userList = query(sqlBase, paramsBase,
					getBeanPropertyRowMapper(UserInfo.class));
		} catch (Exception e) {
			Logger.getRootLogger().info("exception" + e.getMessage());
			e.printStackTrace();
		}
		
		return userList;
	}
	
	/**
	 * 编辑用户
	 * @param user
	 * @return
	 * @throws SQLException
	 */
	public int editUser(UserInfo user) throws SQLException {
		return 1;
	}
	
	/**
	 * 不分页，查询所有数据
	 * 
	 * @return
	 * @throws SQLException
	 */
	public List<MapBean> getUserListAll() throws SQLException {
		List<MapBean> dataList = DBTools.table("tb_userinfo").select();
		return dataList;
	}

	public int updateUser(UserInfo user) throws SQLException {
		int r = 0;

		List<Param> pList = new ArrayList<Param>();
		pList.add(new Param(user.getUserName(), ColumnType.VARCHAR));

		List<Column> cList = new ArrayList<Column>();
		cList.add(new Column("USER_PWD", user.getUserPwd(), ColumnType.VARCHAR));//
		cList.add(new Column("USER_NICK", user.getUserNick(), ColumnType.VARCHAR));//
		cList.add(new Column("USER_TYPE", user.getUserType(), ColumnType.VARCHAR)); //
		cList.add(new Column("USER_EMAIL", user.getUserEmail(), ColumnType.VARCHAR)); //

		if (CommonUtils.isNotNull(user.getUserPhone())) {
			cList.add(new Column("USER_PHONE", user.getUserPhone(), ColumnType.VARCHAR)); //
		}
		if (CommonUtils.isNotNull(user.getUserPicUrl())) {
			cList.add(new Column("USER_PIC_URL", user.getUserPicUrl(), ColumnType.VARCHAR)); //
		}
		if (CommonUtils.isNotNull(user.getUserDescription())) {
			cList.add(new Column("USER_DESCRIPTION", user.getUserDescription(), ColumnType.VARCHAR)); //
		}
		if (CommonUtils.isNotNull(user.getIsForbid())) {
			cList.add(new Column("IS_FORBID", user.getIsForbid(), ColumnType.VARCHAR)); //
		}
		if (CommonUtils.isNotNull(user.getForbidReason())) {
			cList.add(new Column("FORBID_REASON", user.getForbidReason(), ColumnType.VARCHAR)); //
		}
		if (CommonUtils.isNotNull(user.getCreatTime())) {
			cList.add(new Column("CREAT_TIME", user.getCreatTime(), ColumnType.TIMESTAMP)); //
		}
		if (CommonUtils.isNotNull(user.getLastModifyTime())) {
			cList.add(new Column("LAST_MODIFY_TIME", user.getLastModifyTime(), ColumnType.TIMESTAMP)); //
		}
		if (CommonUtils.isNotNull(user.getLastModifyUser())) {
			cList.add(new Column("LAST_MODIFY_USER", user.getLastModifyUser(), ColumnType.VARCHAR)); //
		}
		if (CommonUtils.isNotNull(user.getLastLoginTime())) {
			cList.add(new Column("LAST_LOGIN_TIME", user.getLastLoginTime(), ColumnType.TIMESTAMP)); //
		}

		r = DBTools.table("tb_userinfo").where(" USER_NAME = ? ", pList).update(cList);

		return r;
	}

	public int delUser(UserInfo user) throws SQLException {
		int r = 0;
		List<Param> pList = new ArrayList<Param>();
		pList.add(new Param(user.getUserName(), ColumnType.VARCHAR));
		r = DBTools.table("tb_userinfo").where(" USER_NAME = ? ", pList).delete();
		return r;
	}

}
